package com.hk.service.demo.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hk.domain.entity.User;
import com.hk.enums.YxbzEnum;
import com.hk.mapper.UserMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hk.service.demo.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 第一张测试表 服务实现类
 * </p>
 *
 * @author yixin
 * @since 2023-02-12
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {



    @Cacheable(value = "all_user_data", key = "'get_all_user_'")
    public List<User> getAllUser() {
        List<User> list = list(new LambdaQueryWrapper<>());
        return list;
    }

    /**
     * key 是一个EL表达式
     * @param username
     * @return
     */
    @Cacheable(cacheNames = {"userInfo"}, key = "#username")
    @Override
    public User queryUserByName(String username) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<User>()
                .apply("yxbz = 'Y'")
                .eq(User::getUsername, username);
        User user = getOne(lambdaQueryWrapper);
        return user;
    }

    /**
     * 查询用户信息 如果返回结果result为空就不会进行缓存，不为空才会缓存
     * @param username
     * @return
     */
    @Cacheable(cacheNames = {"NoNullUserValue"}, key = "#username", unless = "#result==null")
    @Override
    public User queryUserHaveNull(String username) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<User>()
                .apply("yxbz = 'Y'")
                .eq(User::getUsername, username);
        User user = getOne(lambdaQueryWrapper);
        return user;
    }


    /**
     * 删除 NoNullUserValue中key为#username的缓存
     * @param username
     */
    @CacheEvict(cacheNames = "NoNullUserValue", key = "#username")
    @Override
    public void deleteUserHaveNullData(String username) {
        log.info("删除 {} 用户的信息", username);
    }


    @Override
    public boolean removeData(String username, String password) {
        Map<String, Object> map = new HashMap<>(2);
        map.put("username", username);
        map.put("password", password);
        map.put("Yxbz", YxbzEnum.Y.name());
        return removeByMap(map);
    }

}
